package cn.ac.cintcm.prespring.util;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class StringUtil {

    private static final int ID_SIZE = 6;

    public static String array2String(List<String> list, String seperator) {
        StringBuilder values = new StringBuilder();
        String returnValue = "";
        if (list != null && seperator != null) {
            for (String str : list) {
                values.append(str);
                values.append(seperator);
            }
            if (values.length() > 0) {
                returnValue = values.toString().substring(
                        0, values.length() - seperator.length());
            }
        }
        return returnValue;
    }

    public static CharSequence map2String(HashMap<String, Integer> map, 
            String fieldSeperator, String seperator) {
        StringBuilder values = new StringBuilder();
        String returnValue = null;
        if (map != null && seperator != null) {
            List<Map.Entry<String, Integer>> list = sortMap(map);
            for (Map.Entry<String, Integer> str : list) {
                values.append(str.getKey());
                values.append(fieldSeperator);
                values.append(str.getValue());
                values.append(seperator);
            }
            returnValue = values.toString().substring(0, values.length() - seperator.length());
        }
        return returnValue;
    }
    
    public static List<Map.Entry<String, Integer>>  sortMap(Map<String, Integer> map) {
        List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(map.entrySet());

        java.util.Collections.sort(list, new Comparator<Map.Entry<String, Integer>>(){
            public int compare(Map.Entry<String, Integer> entry, Map.Entry<String, Integer> entry1)
            {
                return (entry.getValue().equals(entry1.getValue()) ? 0 :
                    (entry.getValue() > entry1.getValue() ? 1 : -1));
            }
        });
        return list;
    }
    
    public static List<Integer> string2List(String s) {
        List<Integer> list = null;
        if (s != null) {
            list = new ArrayList<Integer>();
            String[] elements = s.split(Config.ITEM_SPLITTER);
            for (String es : elements) {
                list.add(Integer.parseInt(es));
            }
        }
        return list;
    }
    
    public static String getId(Integer i) {
        StringBuilder str = new StringBuilder();
        String element = i + "";
        for (int j = 0; j < ID_SIZE - element.length(); j++) {
            str.append("0");
        }
        str.append(i);
        return str.toString();
    }
}
